<template>
    <div class="song-list">
        <div class="music-list-header">
            <div class="title">全部音乐</div>
            <div class="music-cover"></div>
            <n-button type="primary" class="btn" @click="randomPlay">
                全部随机播放
            </n-button>
            <n-button type="primary" class="btn" @click="sequencePlay">
                全部顺序播放
            </n-button>
        </div>
        <n-infinite-scroll
            style="height: calc(100% - 34px)"
            :distance="10"
            @load="handleLoad"
        >
            <song-item
                v-for="(song, index) of songList"
                :key="song.id"
                :song="song"
                :index="index"
                :type="SONG_ITEM_TYPE.LARGE"
                play-on-click
                :opts="['add-to-ready-list', 'star']"
            ></song-item>
        </n-infinite-scroll>
    </div>
</template>

<script lang="ts" setup>
import { ref, defineComponent, onMounted, Ref } from "vue";
import SongItem from "@/components/song-item.vue";
import { selectSongPageData } from "@/api/modules/song";
import { AxiosResponse } from "axios";
import { ISongItem } from "@/types/song-item";
import { useStore } from "vuex";
import { NButton, NInfiniteScroll } from "naive-ui";
import { SONG_ITEM_TYPE } from "@/constant/song";
const store = useStore();
const numPerPage = 20;
const isLoading = ref(false);

const songList: Ref<Array<ISongItem>> = ref([]);
const start: Ref<number> = ref(0);
const end: Ref<number> = ref(numPerPage);

const loadData = function () {
    if (isLoading.value) return;
    isLoading.value = true;
    selectSongPageData({
        _end: end.value,
        _order: "ASC",
        _sort: "title",
        _start: start.value,
        title: "",
    }).then((res: AxiosResponse) => {
        start.value += numPerPage;
        end.value += numPerPage;
        songList.value.push(...res.data);
        setTimeout(() => {
            isLoading.value = false;
        }, 300);
    });
};

const handleLoad = function () {
    loadData();
};

onMounted(() => {
    loadData();
});

defineComponent({
    components: {
        NButton,
        NInfiniteScroll,
    },
});

// 随机播放
const randomPlay = function () {
    // 添加到待播放列表
    store.dispatch("play/add2ReadyList", songList.value);
    // 竞选当前播放的歌曲
    store.dispatch("play/campaign4Song");
};

const sequencePlay = function () {
    // 添加到待播放列表
    store.dispatch("play/add2ReadyList", songList.value);
    // 播放第一首
    store.dispatch("play/updatePlayingInfo", songList.value[0]);
};
</script>
<style lang="less" scoped>
.song-list {
    height: 100%;
    background: #121212;
    .music-list-header {
        height: 34px;
        display: flex;
        justify-content: flex-start;
        padding-left: 50px;
        .btn {
            margin-right: 15px;
        }
    }
}
</style>
